home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part03 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.1 KB

  1. Subject:  v22i089:  GNU AWK, version 2.11, Part03/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: 18ccb1bd ddb6cf98 d87e1396 ed05c1c0
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 89
  8. Archive-name: gawk2.11/part03
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.texinfo.04 ./missing.d/strtod.c
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:47 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 3 (of 16)."'
  21. if test -f './gawk.texinfo.04' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'./gawk.texinfo.04'\"
  23. else
  24.   echo shar: Extracting \"'./gawk.texinfo.04'\" \(49666 characters\)
  25.   sed "s/^X//" >'./gawk.texinfo.04' <<'END_OF_FILE'
  26. Xoften necessary to insure that it happens where you want it to by
  27. Xenclosing the items to be concatenated in parentheses.  For example, the
  28. Xfollowing code fragment does not concatenate @code{file} and @code{name}
  29. Xas you might expect:
  30. X
  31. X@example
  32. Xfile = "file"
  33. Xname = "name"
  34. Xprint "something meaningful" > file name
  35. X@end example
  36. X
  37. X@noindent
  38. XIt is necessary to use the following:
  39. X
  40. X@example
  41. Xprint "something meaningful" > (file name)
  42. X@end example
  43. X
  44. XWe recommend you use parentheses around concatenation in all but the
  45. Xmost common contexts (such as in the right-hand operand of @samp{=}).
  46. X
  47. X@ignore
  48. X@code{gawk} actually now allows a concatenation on the right hand
  49. Xside of a @code{>} redirection, but other @code{awk}s don't.  So for
  50. Xnow we won't mention that fact.
  51. X@end ignore
  52. X
  53. X@node Comparison Ops, Boolean Ops, Concatenation, Expressions
  54. X@section Comparison Expressions
  55. X@cindex comparison expressions
  56. X@cindex expressions, comparison
  57. X@cindex relational operators
  58. X@cindex operators, relational
  59. X@cindex regexp operators
  60. X
  61. X@dfn{Comparison expressions} compare strings or numbers for
  62. Xrelationships such as equality.  They are written using @dfn{relational
  63. Xoperators}, which are a superset of those in C.  Here is a table of
  64. Xthem:
  65. X
  66. X@table @code
  67. X@item @var{x} < @var{y}
  68. XTrue if @var{x} is less than @var{y}.
  69. X
  70. X@item @var{x} <= @var{y}
  71. XTrue if @var{x} is less than or equal to @var{y}.
  72. X
  73. X@item @var{x} > @var{y}
  74. XTrue if @var{x} is greater than @var{y}.
  75. X
  76. X@item @var{x} >= @var{y}
  77. XTrue if @var{x} is greater than or equal to @var{y}.
  78. X
  79. X@item @var{x} == @var{y}
  80. XTrue if @var{x} is equal to @var{y}.
  81. X
  82. X@item @var{x} != @var{y}
  83. XTrue if @var{x} is not equal to @var{y}.
  84. X
  85. X@item @var{x} ~ @var{y}
  86. XTrue if the string @var{x} matches the regexp denoted by @var{y}.
  87. X
  88. X@item @var{x} !~ @var{y}
  89. XTrue if the string @var{x} does not match the regexp denoted by @var{y}.
  90. X
  91. X@item @var{subscript} in @var{array}
  92. XTrue if array @var{array} has an element with the subscript @var{subscript}.
  93. X@end table
  94. X
  95. XComparison expressions have the value 1 if true and 0 if false.
  96. X
  97. XThe operands of a relational operator are compared as numbers if they
  98. Xare both numbers.  Otherwise they are converted to, and compared as,
  99. Xstrings (@pxref{Conversion}).  Strings are compared by comparing the
  100. Xfirst character of each, then the second character of each, and so on.
  101. XThus, @code{"10"} is less than @code{"9"}.
  102. X
  103. XFor example,
  104. X
  105. X@example
  106. X$1 == "foo"
  107. X@end example
  108. X
  109. X@noindent
  110. Xhas the value of 1, or is true, if the first field of the current input
  111. Xrecord is precisely @samp{foo}.  By contrast, 
  112. X
  113. X@example
  114. X$1 ~ /foo/
  115. X@end example
  116. X
  117. X@noindent
  118. Xhas the value 1 if the first field contains @samp{foo}.
  119. X
  120. XThe right hand operand of the @samp{~} and @samp{!~} operators may be
  121. Xeither a constant regexp (@code{/@dots{}/}), or it may be an ordinary
  122. Xexpression, in which case the value of the expression as a string is a
  123. Xdynamic regexp (@pxref{Regexp Usage}).
  124. X
  125. X@cindex regexp as expression
  126. XIn very recent implementations of @code{awk}, a constant regular
  127. Xexpression in slashes by itself is also an expression.  The regexp
  128. X@code{/@var{regexp}/} is an abbreviation for this comparison expression:
  129. X
  130. X@example
  131. X$0 ~ /@var{regexp}/
  132. X@end example
  133. X
  134. XIn some contexts it may be necessary to write parentheses around the
  135. Xregexp to avoid confusing the @code{gawk} parser.  For example,
  136. X@code{(/x/ - /y/) > threshold} is not allowed, but @code{((/x/) - (/y/))
  137. X> threshold} parses properly.
  138. X
  139. XOne special place where @code{/foo/} is @emph{not} an abbreviation for
  140. X@code{$0 ~ /foo/} is when it is the right-hand operand of @samp{~} or
  141. X@samp{!~}!
  142. X
  143. X@node Boolean Ops, Assignment Ops, Comparison Ops, Expressions
  144. X@section Boolean Expressions
  145. X@cindex expressions, boolean
  146. X@cindex boolean expressions
  147. X@cindex operators, boolean
  148. X@cindex boolean operators
  149. X@cindex logical operations
  150. X@cindex and operator
  151. X@cindex or operator
  152. X@cindex not operator
  153. X
  154. XA @dfn{boolean expression} is combination of comparison expressions or
  155. Xmatching expressions, using the @dfn{boolean operators} ``or''
  156. X(@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}), along with
  157. Xparentheses to control nesting.  The truth of the boolean expression is
  158. Xcomputed by combining the truth values of the component expressions.
  159. X
  160. XBoolean expressions can be used wherever comparison and matching
  161. Xexpressions can be used.  They can be used in @code{if} and @code{while}
  162. Xstatements.  They have numeric values (1 if true, 0 if false), which
  163. Xcome into place if the result of the boolean expression is stored in a
  164. Xvariable, or used in arithmetic.
  165. X
  166. XIn addition, every boolean expression is also a valid boolean pattern, so
  167. Xyou can use it as a pattern to control the execution of rules.
  168. X
  169. XHere are descriptions of the three boolean operators, with an example of
  170. Xeach.  It may be instructive to compare these examples with the
  171. Xanalogous examples of boolean patterns (@pxref{Boolean Patterns}), which
  172. Xuse the same boolean operators in patterns instead of expressions.
  173. X
  174. X@table @code
  175. X@item @var{boolean1} && @var{boolean2}
  176. XTrue if both @var{boolean1} and @var{boolean2} are true.  For example,
  177. Xthe following statement prints the current input record if it contains
  178. Xboth @samp{2400} and @samp{foo}.@refill
  179. X
  180. X@example
  181. Xif ($0 ~ /2400/ && $0 ~ /foo/) print
  182. X@end example
  183. X
  184. XThe subexpression @var{boolean2} is evaluated only if @var{boolean1}
  185. Xis true.  This can make a difference when @var{boolean2} contains
  186. Xexpressions that have side effects: in the case of @code{$0 ~ /foo/ &&
  187. X($2 == bar++)}, the variable @code{bar} is not incremented if there is
  188. Xno @samp{foo} in the record.
  189. X
  190. X@item @var{boolean1} || @var{boolean2}
  191. XTrue if at least one of @var{boolean1} and @var{boolean2} is true.
  192. XFor example, the following command prints all records in the input
  193. Xfile @file{BBS-list} that contain @emph{either} @samp{2400} or
  194. X@samp{foo}, or both.@refill
  195. X
  196. X@example
  197. Xawk '@{ if ($0 ~ /2400/ || $0 ~ /foo/) print @}' BBS-list
  198. X@end example
  199. X
  200. XThe subexpression @var{boolean2} is evaluated only if @var{boolean1}
  201. Xis false.  This can make a difference when @var{boolean2} contains
  202. Xexpressions that have side effects.
  203. X
  204. X@item !@var{boolean}
  205. XTrue if @var{boolean} is false.  For example, the following program prints
  206. Xall records in the input file @file{BBS-list} that do @emph{not} contain the
  207. Xstring @samp{foo}.
  208. X
  209. X@example
  210. Xawk '@{ if (! ($0 ~ /foo/)) print @}' BBS-list
  211. X@end example
  212. X@end table
  213. X
  214. X@node Assignment Ops, Increment Ops, Boolean Ops, Expressions
  215. X@section Assignment Expressions
  216. X@cindex assignment operators
  217. X@cindex operators, assignment
  218. X@cindex expressions, assignment
  219. X
  220. XAn @dfn{assignment} is an expression that stores a new value into a
  221. Xvariable.  For example, let's assign the value 1 to the variable
  222. X@code{z}:@refill
  223. X
  224. X@example
  225. Xz = 1
  226. X@end example
  227. X
  228. XAfter this expression is executed, the variable @code{z} has the value 1.
  229. XWhatever old value @code{z} had before the assignment is forgotten.
  230. X
  231. XAssignments can store string values also.  For example, this would store
  232. Xthe value @code{"this food is good"} in the variable @code{message}:
  233. X
  234. X@example
  235. Xthing = "food"
  236. Xpredicate = "good"
  237. Xmessage = "this " thing " is " predicate
  238. X@end example
  239. X
  240. X@noindent
  241. X(This also illustrates concatenation of strings.)
  242. X
  243. XThe @samp{=} sign is called an @dfn{assignment operator}.  It is the
  244. Xsimplest assignment operator because the value of the right-hand
  245. Xoperand is stored unchanged.
  246. X
  247. X@cindex side effect
  248. XMost operators (addition, concatenation, and so on) have no effect
  249. Xexcept to compute a value.  If you ignore the value, you might as well
  250. Xnot use the operator.  An assignment operator is different; it does
  251. Xproduce a value, but even if you ignore the value, the assignment still
  252. Xmakes itself felt through the alteration of the variable.  We call this
  253. Xa @dfn{side effect}.
  254. X
  255. X@cindex lvalue
  256. XThe left-hand operand of an assignment need not be a variable
  257. X(@pxref{Variables}); it can also be a field (@pxref{Changing Fields}) or
  258. Xan array element (@pxref{Arrays}).  These are all called @dfn{lvalues},
  259. Xwhich means they can appear on the left-hand side of an assignment operator.
  260. XThe right-hand operand may be any expression; it produces the new value
  261. Xwhich the assignment stores in the specified variable, field or array
  262. Xelement.
  263. X
  264. XIt is important to note that variables do @emph{not} have permanent types.
  265. XThe type of a variable is simply the type of whatever value it happens
  266. Xto hold at the moment.  In the following program fragment, the variable
  267. X@code{foo} has a numeric value at first, and a string value later on:
  268. X
  269. X@example
  270. Xfoo = 1
  271. Xprint foo
  272. Xfoo = "bar"
  273. Xprint foo
  274. X@end example
  275. X
  276. X@noindent
  277. XWhen the second assignment gives @code{foo} a string value, the fact that
  278. Xit previously had a numeric value is forgotten.
  279. X
  280. XAn assignment is an expression, so it has a value: the same value that
  281. Xis assigned.  Thus, @code{z = 1} as an expression has the value 1.
  282. XOne consequence of this is that you can write multiple assignments together:
  283. X
  284. X@example
  285. Xx = y = z = 0
  286. X@end example
  287. X
  288. X@noindent
  289. Xstores the value 0 in all three variables.  It does this because the
  290. Xvalue of @code{z = 0}, which is 0, is stored into @code{y}, and then
  291. Xthe value of @code{y = z = 0}, which is 0, is stored into @code{x}.
  292. X
  293. XYou can use an assignment anywhere an expression is called for.  For
  294. Xexample, it is valid to write @code{x != (y = 1)} to set @code{y} to 1
  295. Xand then test whether @code{x} equals 1.  But this style tends to make
  296. Xprograms hard to read; except in a one-shot program, you should
  297. Xrewrite it to get rid of such nesting of assignments.  This is never very
  298. Xhard.
  299. X
  300. XAside from @samp{=}, there are several other assignment operators that
  301. Xdo arithmetic with the old value of the variable.  For example, the
  302. Xoperator @samp{+=} computes a new value by adding the right-hand value
  303. Xto the old value of the variable.  Thus, the following assignment adds
  304. X5 to the value of @code{foo}:
  305. X
  306. X@example
  307. Xfoo += 5
  308. X@end example
  309. X
  310. X@noindent
  311. XThis is precisely equivalent to the following:
  312. X
  313. X@example
  314. Xfoo = foo + 5
  315. X@end example
  316. X
  317. X@noindent
  318. XUse whichever one makes the meaning of your program clearer.
  319. X
  320. XHere is a table of the arithmetic assignment operators.  In each
  321. Xcase, the right-hand operand is an expression whose value is converted
  322. Xto a number.
  323. X
  324. X@table @code
  325. X@item @var{lvalue} += @var{increment}
  326. XAdds @var{increment} to the value of @var{lvalue} to make the new value
  327. Xof @var{lvalue}.
  328. X
  329. X@item @var{lvalue} -= @var{decrement}
  330. XSubtracts @var{decrement} from the value of @var{lvalue}.
  331. X
  332. X@item @var{lvalue} *= @var{coefficient}
  333. XMultiplies the value of @var{lvalue} by @var{coefficient}.
  334. X
  335. X@item @var{lvalue} /= @var{quotient}
  336. XDivides the value of @var{lvalue} by @var{quotient}.
  337. X
  338. X@item @var{lvalue} %= @var{modulus}
  339. XSets @var{lvalue} to its remainder by @var{modulus}.
  340. X
  341. X@item @var{lvalue} ^= @var{power}
  342. X@itemx @var{lvalue} **= @var{power}
  343. XRaises @var{lvalue} to the power @var{power}.
  344. X@end table
  345. X
  346. X@node Increment Ops, Conversion, Assignment Ops, Expressions
  347. X@section Increment Operators
  348. X
  349. X@cindex increment operators
  350. X@cindex operators, increment
  351. X@dfn{Increment operators} increase or decrease the value of a variable
  352. Xby 1.  You could do the same thing with an assignment operator, so
  353. Xthe increment operators add no power to the @code{awk} language; but they
  354. Xare convenient abbreviations for something very common.
  355. X
  356. XThe operator to add 1 is written @samp{++}.  It can be used to increment
  357. Xa variable either before or after taking its value.
  358. X
  359. XTo pre-increment a variable @var{v}, write @code{++@var{v}}.  This adds
  360. X1 to the value of @var{v} and that new value is also the value of this
  361. Xexpression.  The assignment expression @code{@var{v} += 1} is completely
  362. Xequivalent.
  363. X
  364. XWriting the @samp{++} after the variable specifies post-increment.  This
  365. Xincrements the variable value just the same; the difference is that the
  366. Xvalue of the increment expression itself is the variable's @emph{old}
  367. Xvalue.  Thus, if @code{foo} has value 4, then the expression @code{foo++}
  368. Xhas the value 4, but it changes the value of @code{foo} to 5.
  369. X
  370. XThe post-increment @code{foo++} is nearly equivalent to writing @code{(foo
  371. X+= 1) - 1}.  It is not perfectly equivalent because all numbers in
  372. X@code{awk} are floating point: in floating point, @code{foo + 1 - 1} does
  373. Xnot necessarily equal @code{foo}.  But the difference is minute as
  374. Xlong as you stick to numbers that are fairly small (less than a trillion).
  375. X
  376. XAny lvalue can be incremented.  Fields and array elements are incremented
  377. Xjust like variables.
  378. X
  379. XThe decrement operator @samp{--} works just like @samp{++} except that
  380. Xit subtracts 1 instead of adding.  Like @samp{++}, it can be used before
  381. Xthe lvalue to pre-decrement or after it to post-decrement.
  382. X
  383. XHere is a summary of increment and decrement expressions.
  384. X
  385. X@table @code
  386. X@item ++@var{lvalue}
  387. XThis expression increments @var{lvalue} and the new value becomes the
  388. Xvalue of this expression.
  389. X
  390. X@item @var{lvalue}++
  391. XThis expression causes the contents of @var{lvalue} to be incremented.
  392. XThe value of the expression is the @emph{old} value of @var{lvalue}.
  393. X
  394. X@item --@var{lvalue}
  395. XLike @code{++@var{lvalue}}, but instead of adding, it subtracts.  It
  396. Xdecrements @var{lvalue} and delivers the value that results.
  397. X
  398. X@item @var{lvalue}--
  399. XLike @code{@var{lvalue}++}, but instead of adding, it subtracts.  It
  400. Xdecrements @var{lvalue}.  The value of the expression is the @emph{old}
  401. Xvalue of @var{lvalue}.
  402. X@end table
  403. X
  404. X@node Conversion, Conditional Exp, Increment Ops, Expressions
  405. X@section Conversion of Strings and Numbers
  406. X
  407. X@cindex conversion of strings and numbers
  408. XStrings are converted to numbers, and numbers to strings, if the context
  409. Xof the @code{awk} program demands it.  For example, if the value of
  410. Xeither @code{foo} or @code{bar} in the expression @code{foo + bar}
  411. Xhappens to be a string, it is converted to a number before the addition
  412. Xis performed.  If numeric values appear in string concatenation, they
  413. Xare converted to strings.  Consider this:@refill
  414. X
  415. X@example
  416. Xtwo = 2; three = 3
  417. Xprint (two three) + 4
  418. X@end example
  419. X
  420. X@noindent
  421. XThis eventually prints the (numeric) value 27.  The numeric values of
  422. Xthe variables @code{two} and @code{three} are converted to strings and
  423. Xconcatenated together, and the resulting string is converted back to the
  424. Xnumber 23, to which 4 is then added.
  425. X
  426. XIf, for some reason, you need to force a number to be converted to a
  427. Xstring, concatenate the null string with that number.  To force a string
  428. Xto be converted to a number, add zero to that string.
  429. X
  430. XStrings are converted to numbers by interpreting them as numerals:
  431. X@code{"2.5"} converts to 2.5, and @code{"1e3"} converts to 1000.
  432. XStrings that can't be interpreted as valid numbers are converted to
  433. Xzero.
  434. X
  435. X@vindex OFMT
  436. XThe exact manner in which numbers are converted into strings is controlled
  437. Xby the @code{awk} built-in variable @code{OFMT} (@pxref{Built-in Variables}).
  438. XNumbers are converted using a special
  439. Xversion of the @code{sprintf} function (@pxref{Built-in}) with @code{OFMT}
  440. Xas the format specifier.@refill
  441. X
  442. X@code{OFMT}'s default value is @code{"%.6g"}, which prints a value with
  443. Xat least six significant digits.  For some applications you will want to
  444. Xchange it to specify more precision.  Double precision on most modern
  445. Xmachines gives you 16 or 17 decimal digits of precision.
  446. X
  447. XStrange results can happen if you set @code{OFMT} to a string that doesn't
  448. Xtell @code{sprintf} how to format floating point numbers in a useful way.
  449. XFor example, if you forget the @samp{%} in the format, all numbers will be
  450. Xconverted to the same constant string.@refill
  451. X
  452. X@node Conditional Exp, Function Calls, Conversion, Expressions
  453. X@section Conditional Expressions
  454. X@cindex conditional expression
  455. X@cindex expression, conditional
  456. X
  457. XA @dfn{conditional expression} is a special kind of expression with
  458. Xthree operands.  It allows you to use one expression's value to select
  459. Xone of two other expressions.
  460. X
  461. XThe conditional expression looks the same as in the C language:
  462. X
  463. X@example
  464. X@var{selector} ? @var{if-true-exp} : @var{if-false-exp}
  465. X@end example
  466. X
  467. X@noindent
  468. XThere are three subexpressions.  The first, @var{selector}, is always
  469. Xcomputed first.  If it is ``true'' (not zero) then @var{if-true-exp} is
  470. Xcomputed next and its value becomes the value of the whole expression.
  471. XOtherwise, @var{if-false-exp} is computed next and its value becomes the
  472. Xvalue of the whole expression.
  473. X
  474. XFor example, this expression produces the absolute value of @code{x}:
  475. X
  476. X@example
  477. Xx > 0 ? x : -x
  478. X@end example
  479. X
  480. XEach time the conditional expression is computed, exactly one of
  481. X@var{if-true-exp} and @var{if-false-exp} is computed; the other is ignored.
  482. XThis is important when the expressions contain side effects.  For example,
  483. Xthis conditional expression examines element @code{i} of either array
  484. X@code{a} or array @code{b}, and increments @code{i}.
  485. X
  486. X@example
  487. Xx == y ? a[i++] : b[i++]
  488. X@end example
  489. X
  490. X@noindent
  491. XThis is guaranteed to increment @code{i} exactly once, because each time
  492. Xone or the other of the two increment expressions is executed,
  493. Xand the other is not.
  494. X
  495. X@node Function Calls, Precedence, Conditional Exp, Expressions
  496. X@section Function Calls
  497. X@cindex function call
  498. X@cindex calling a function
  499. X
  500. XA @dfn{function} is a name for a particular calculation.  Because it has
  501. Xa name, you can ask for it by name at any point in the program.  For
  502. Xexample, the function @code{sqrt} computes the square root of a number.
  503. X
  504. XA fixed set of functions are @dfn{built in}, which means they are
  505. Xavailable in every @code{awk} program.  The @code{sqrt} function is one
  506. Xof these.  @xref{Built-in}, for a list of built-in functions and their
  507. Xdescriptions.  In addition, you can define your own functions in the
  508. Xprogram for use elsewhere in the same program.  @xref{User-defined},
  509. Xfor how to do this.
  510. X
  511. X@cindex arguments in function call
  512. XThe way to use a function is with a @dfn{function call} expression,
  513. Xwhich consists of the function name followed by a list of
  514. X@dfn{arguments} in parentheses.  The arguments are expressions which
  515. Xgive the raw materials for the calculation that the function will do.
  516. XWhen there is more than one argument, they are separated by commas.  If
  517. Xthere are no arguments, write just @samp{()} after the function name.
  518. XHere are some examples:
  519. X
  520. X@example
  521. Xsqrt(x**2 + y**2)    # @r{One argument}
  522. Xatan2(y, x)          # @r{Two arguments}
  523. Xrand()               # @r{No arguments}
  524. X@end example
  525. X
  526. X@strong{Do not put any space between the function name and the
  527. Xopen-parenthesis!}  A user-defined function name looks just like the name of
  528. Xa variable, and space would make the expression look like concatenation
  529. Xof a variable with an expression inside parentheses.  Space before the
  530. Xparenthesis is harmless with built-in functions, but it is best not to get
  531. Xinto the habit of using space, lest you do likewise for a user-defined
  532. Xfunction one day by mistake.
  533. X
  534. XEach function expects a particular number of arguments.  For example, the
  535. X@code{sqrt} function must be called with a single argument, the number
  536. Xto take the square root of:
  537. X
  538. X@example
  539. Xsqrt(@var{argument})
  540. X@end example
  541. X
  542. XSome of the built-in functions allow you to omit the final argument.
  543. XIf you do so, they use a reasonable default.  @xref{Built-in},
  544. Xfor full details.  If arguments are omitted in calls to user-defined
  545. Xfunctions, then those arguments are treated as local variables,
  546. Xinitialized to the null string (@pxref{User-defined}).
  547. X
  548. XLike every other expression, the function call has a value, which is
  549. Xcomputed by the function based on the arguments you give it.  In this
  550. Xexample, the value of @code{sqrt(@var{argument})} is the square root of the
  551. Xargument.  A function can also have side effects, such as assigning the
  552. Xvalues of certain variables or doing I/O.
  553. X
  554. XHere is a command to read numbers, one number per line, and print the
  555. Xsquare root of each one:
  556. X
  557. X@example
  558. Xawk '@{ print "The square root of", $1, "is", sqrt($1) @}'
  559. X@end example
  560. X
  561. X@node Precedence,, Function Calls, Expressions
  562. X@section Operator Precedence: How Operators Nest
  563. X@cindex precedence
  564. X@cindex operator precedence
  565. X
  566. X@dfn{Operator precedence} determines how operators are grouped, when
  567. Xdifferent operators appear close by in one expression.  For example,
  568. X@samp{*} has higher precedence than @samp{+}; thus, @code{a + b * c}
  569. Xmeans to multiply @code{b} and @code{c}, and then add @code{a} to the
  570. Xproduct.
  571. X
  572. XYou can overrule the precedence of the operators by writing parentheses
  573. Xyourself.  You can think of the precedence rules as saying where the
  574. Xparentheses are assumed if you do not write parentheses yourself.  In
  575. Xfact, it is wise always to use parentheses whenever you have an unusual
  576. Xcombination of operators, because other people who read the program may
  577. Xnot remember what the precedence is in this case.  You might forget,
  578. Xtoo; then you could make a mistake.  Explicit parentheses will prevent
  579. Xany such mistake.
  580. X
  581. XWhen operators of equal precedence are used together, the leftmost
  582. Xoperator groups first, except for the assignment, conditional and
  583. Xand exponentiation operators, which group in the opposite order.
  584. XThus, @code{a - b + c} groups as @code{(a - b) + c};
  585. X@code{a = b = c} groups as @code{a = (b = c)}.
  586. X
  587. XThe precedence of prefix unary operators does not matter as long as only
  588. Xunary operators are involved, because there is only one way to parse
  589. Xthem---innermost first.  Thus, @code{$++i} means @code{$(++i)} and
  590. X@code{++$x} means @code{++($x)}.  However, when another operator follows
  591. Xthe operand, then the precedence of the unary operators can matter.
  592. XThus, @code{$x**2} means @code{($x)**2}, but @code{-x**2} means
  593. X@code{-(x**2)}, because @samp{-} has lower precedence than @samp{**}
  594. Xwhile @samp{$} has higher precedence.
  595. X
  596. XHere is a table of the operators of @code{awk}, in order of increasing
  597. Xprecedence:
  598. X
  599. X@table @asis
  600. X@item assignment
  601. X@samp{=}, @samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{%=},
  602. X@samp{^=}, @samp{**=}.  These operators group right-to-left.
  603. X
  604. X@item conditional
  605. X@samp{?:}.  These operators group right-to-left.
  606. X
  607. X@item logical ``or''.
  608. X@samp{||}.
  609. X
  610. X@item logical ``and''.
  611. X@samp{&&}.
  612. X
  613. X@item array membership
  614. X@code{in}.
  615. X
  616. X@item matching
  617. X@samp{~}, @samp{!~}.
  618. X
  619. X@item relational, and redirection
  620. XThe relational operators and the redirections have the same precedence
  621. Xlevel.  Characters such as @samp{>} serve both as relationals and as
  622. Xredirections; the context distinguishes between the two meanings.
  623. X
  624. XThe relational operators are @samp{<}, @samp{<=}, @samp{==}, @samp{!=},
  625. X@samp{>=} and @samp{>}.
  626. X
  627. XThe I/O redirection operators are @samp{<}, @samp{>}, @samp{>>} and
  628. X@samp{|}.
  629. X
  630. XNote that I/O redirection operators in @code{print} and @code{printf}
  631. Xstatements belong to the statement level, not to expressions.  The
  632. Xredirection does not produce an expression which could be the operand of
  633. Xanother operator.  As a result, it does not make sense to use a
  634. Xredirection operator near another operator of lower precedence, without
  635. Xparentheses.  Such combinations, for example @samp{print foo > a ? b :
  636. Xc}, result in syntax errors.
  637. X
  638. X@item concatentation
  639. XNo special token is used to indicate concatenation.
  640. XThe operands are simply written side by side.
  641. X@c This is supposedly being fixed
  642. X@ignore
  643. XConcatenation has the same precedence as relational and redirection
  644. Xoperators.  These operators nest left to right.  Thus, @code{4 5 > 6}
  645. Xconcatenates first, yielding 1, while @code{6 < 4 5} compares first, and
  646. Xyields @code{"05"}.
  647. X@end ignore
  648. X
  649. X@item add, subtract
  650. X@samp{+}, @samp{-}.
  651. X
  652. X@item multiply, divide, mod
  653. X@samp{*}, @samp{/}, @samp{%}.
  654. X
  655. X@item unary plus, minus, ``not''
  656. X@samp{+}, @samp{-}, @samp{!}.
  657. X
  658. X@item exponentiation
  659. X@samp{^}, @samp{**}.  These operators group right-to-left.
  660. X
  661. X@item increment, decrement
  662. X@samp{++}, @samp{--}.
  663. X
  664. X@item field
  665. X@samp{$}.
  666. X@end table
  667. X
  668. X@node Statements, Arrays, Expressions, Top
  669. X@chapter Actions: Control Statements
  670. X@cindex control statement
  671. X
  672. X@dfn{Control statements} such as @code{if}, @code{while}, and so on
  673. Xcontrol the flow of execution in @code{awk} programs.  Most of the
  674. Xcontrol statements in @code{awk} are patterned on similar statements in
  675. XC.
  676. X
  677. XAll the control statements start with special keywords such as @code{if}
  678. Xand @code{while}, to distinguish them from simple expressions.
  679. X
  680. XMany control statements contain other statements; for example, the
  681. X@code{if} statement contains another statement which may or may not be
  682. Xexecuted.  The contained statement is called the @dfn{body}.  If you
  683. Xwant to include more than one statement in the body, group them into a
  684. Xsingle compound statement with curly braces, separating them with
  685. Xnewlines or semicolons.
  686. X
  687. X@menu
  688. X* If Statement::            Conditionally execute some @code{awk} statements.
  689. X
  690. X* While Statement::         Loop until some condition is satisfied.
  691. X
  692. X* Do Statement::            Do specified action while looping until some
  693. X                            condition is satisfied.
  694. X
  695. X* For Statement::           Another looping statement, that provides
  696. X                            initialization and increment clauses.
  697. X
  698. X* Break Statement::         Immediately exit the innermost enclosing loop.
  699. X
  700. X* Continue Statement::      Skip to the end of the innermost enclosing loop.
  701. X
  702. X* Next Statement::          Stop processing the current input record.
  703. X
  704. X* Exit Statement::          Stop execution of @code{awk}.
  705. X@end menu
  706. X
  707. X@node If Statement, While Statement, Statements, Statements
  708. X@section The @code{if} Statement
  709. X
  710. X@cindex @code{if} statement
  711. XThe @code{if}-@code{else} statement is @code{awk}'s decision-making
  712. Xstatement.  It looks like this:@refill
  713. X
  714. X@example
  715. Xif (@var{condition}) @var{then-body} @r{[}else @var{else-body}@r{]}
  716. X@end example
  717. X
  718. X@noindent
  719. XHere @var{condition} is an expression that controls what the rest of the
  720. Xstatement will do.  If @var{condition} is true, @var{then-body} is
  721. Xexecuted; otherwise, @var{else-body} is executed (assuming that the
  722. X@code{else} clause is present).  The @code{else} part of the statement is
  723. Xoptional.  The condition is considered false if its value is zero or
  724. Xthe null string, true otherwise.@refill
  725. X
  726. XHere is an example:
  727. X
  728. X@example
  729. Xif (x % 2 == 0)
  730. X    print "x is even"
  731. Xelse
  732. X    print "x is odd"
  733. X@end example
  734. X
  735. XIn this example, if the expression @code{x % 2 == 0} is true (that is,
  736. Xthe value of @code{x} is divisible by 2), then the first @code{print}
  737. Xstatement is executed, otherwise the second @code{print} statement is
  738. Xperformed.@refill
  739. X
  740. XIf the @code{else} appears on the same line as @var{then-body}, and
  741. X@var{then-body} is not a compound statement (i.e., not surrounded by
  742. Xcurly braces), then a semicolon must separate @var{then-body} from
  743. X@code{else}.  To illustrate this, let's rewrite the previous example:
  744. X
  745. X@group
  746. X@example
  747. Xawk '@{ if (x % 2 == 0) print "x is even"; else
  748. X        print "x is odd" @}'
  749. X@end example
  750. X@end group
  751. X
  752. X@noindent
  753. XIf you forget the @samp{;}, @code{awk} won't be able to parse the
  754. Xstatement, and you will get a syntax error.
  755. X
  756. XWe would not actually write this example this way, because a human
  757. Xreader might fail to see the @code{else} if it were not the first thing
  758. Xon its line.
  759. X
  760. X@node While Statement, Do Statement, If Statement, Statements
  761. X@section The @code{while} Statement
  762. X@cindex @code{while} statement
  763. X@cindex loop
  764. X@cindex body of a loop
  765. X
  766. XIn programming, a @dfn{loop} means a part of a program that is (or at least can
  767. Xbe) executed two or more times in succession.
  768. X
  769. XThe @code{while} statement is the simplest looping statement in
  770. X@code{awk}.  It repeatedly executes a statement as long as a condition is
  771. Xtrue.  It looks like this:
  772. X
  773. X@example
  774. Xwhile (@var{condition})
  775. X  @var{body}
  776. X@end example
  777. X
  778. X@noindent
  779. XHere @var{body} is a statement that we call the @dfn{body} of the loop,
  780. Xand @var{condition} is an expression that controls how long the loop
  781. Xkeeps running.
  782. X
  783. XThe first thing the @code{while} statement does is test @var{condition}.
  784. XIf @var{condition} is true, it executes the statement @var{body}.
  785. X(Truth, as usual in @code{awk}, means that the value of @var{condition}
  786. Xis not zero and not a null string.)  After @var{body} has been executed,
  787. X@var{condition} is tested again, and if it is still true, @var{body} is
  788. Xexecuted again.  This process repeats until @var{condition} is no longer
  789. Xtrue.  If @var{condition} is initially false, the body of the loop is
  790. Xnever executed.@refill
  791. X
  792. XThis example prints the first three fields of each record, one per line.
  793. X
  794. X@example
  795. Xawk '@{ i = 1
  796. X       while (i <= 3) @{
  797. X           print $i
  798. X           i++
  799. X       @}
  800. X@}'
  801. X@end example
  802. X
  803. X@noindent
  804. XHere the body of the loop is a compound statement enclosed in braces,
  805. Xcontaining two statements.
  806. X
  807. XThe loop works like this: first, the value of @code{i} is set to 1.
  808. XThen, the @code{while} tests whether @code{i} is less than or equal to
  809. Xthree.  This is the case when @code{i} equals one, so the @code{i}-th
  810. Xfield is printed.  Then the @code{i++} increments the value of @code{i}
  811. Xand the loop repeats.  The loop terminates when @code{i} reaches 4.
  812. X
  813. XAs you can see, a newline is not required between the condition and the
  814. Xbody; but using one makes the program clearer unless the body is a
  815. Xcompound statement or is very simple.  The newline after the open-brace
  816. Xthat begins the compound statement is not required either, but the
  817. Xprogram would be hard to read without it.
  818. X
  819. X@node Do Statement, For Statement, While Statement, Statements
  820. X@section The @code{do}-@code{while} Statement
  821. X
  822. XThe @code{do} loop is a variation of the @code{while} looping statement.
  823. XThe @code{do} loop executes the @var{body} once, then repeats @var{body}
  824. Xas long as @var{condition} is true.  It looks like this:
  825. X
  826. X@group
  827. X@example
  828. Xdo
  829. X  @var{body}
  830. Xwhile (@var{condition})
  831. X@end example
  832. X@end group
  833. X
  834. XEven if @var{condition} is false at the start, @var{body} is executed at
  835. Xleast once (and only once, unless executing @var{body} makes
  836. X@var{condition} true).  Contrast this with the corresponding
  837. X@code{while} statement:
  838. X
  839. X@example
  840. Xwhile (@var{condition})
  841. X  @var{body}
  842. X@end example
  843. X
  844. X@noindent
  845. XThis statement does not execute @var{body} even once if @var{condition}
  846. Xis false to begin with.
  847. X
  848. XHere is an example of a @code{do} statement:
  849. X
  850. X@example
  851. Xawk '@{ i = 1
  852. X       do @{
  853. X          print $0
  854. X          i++
  855. X       @} while (i <= 10)
  856. X@}'
  857. X@end example
  858. X
  859. X@noindent
  860. Xprints each input record ten times.  It isn't a very realistic example,
  861. Xsince in this case an ordinary @code{while} would do just as well.  But
  862. Xthis reflects actual experience; there is only occasionally a real use
  863. Xfor a @code{do} statement.@refill
  864. X
  865. X@node For Statement, Break Statement, Do Statement, Statements
  866. X@section The @code{for} Statement
  867. X@cindex @code{for} statement
  868. X
  869. XThe @code{for} statement makes it more convenient to count iterations of a
  870. Xloop.  The general form of the @code{for} statement looks like this:@refill
  871. X
  872. X@example
  873. Xfor (@var{initialization}; @var{condition}; @var{increment})
  874. X  @var{body}
  875. X@end example
  876. X
  877. X@noindent
  878. XThis statement starts by executing @var{initialization}.  Then, as long
  879. Xas @var{condition} is true, it repeatedly executes @var{body} and then
  880. X@var{increment}.  Typically @var{initialization} sets a variable to
  881. Xeither zero or one, @var{increment} adds 1 to it, and @var{condition}
  882. Xcompares it against the desired number of iterations.
  883. X
  884. XHere is an example of a @code{for} statement:
  885. X
  886. X@example
  887. Xawk '@{ for (i = 1; i <= 3; i++)
  888. X          print $i
  889. X@}'
  890. X@end example
  891. X
  892. X@noindent
  893. XThis prints the first three fields of each input record, one field per
  894. Xline.
  895. X
  896. XIn the @code{for} statement, @var{body} stands for any statement, but
  897. X@var{initialization}, @var{condition} and @var{increment} are just
  898. Xexpressions.  You cannot set more than one variable in the
  899. X@var{initialization} part unless you use a multiple assignment statement
  900. Xsuch as @code{x = y = 0}, which is possible only if all the initial values
  901. Xare equal.  (But you can initialize additional variables by writing
  902. Xtheir assignments as separate statements preceding the @code{for} loop.)
  903. X
  904. XThe same is true of the @var{increment} part; to increment additional
  905. Xvariables, you must write separate statements at the end of the loop.
  906. XThe C compound expression, using C's comma operator, would be useful in
  907. Xthis context, but it is not supported in @code{awk}.
  908. X
  909. XMost often, @var{increment} is an increment expression, as in the
  910. Xexample above.  But this is not required; it can be any expression
  911. Xwhatever.  For example, this statement prints all the powers of 2
  912. Xbetween 1 and 100:
  913. X
  914. X@example
  915. Xfor (i = 1; i <= 100; i *= 2)
  916. X  print i
  917. X@end example
  918. X
  919. XAny of the three expressions in the parentheses following @code{for} may
  920. Xbe omitted if there is nothing to be done there.  Thus, @w{@samp{for (;x
  921. X> 0;)}} is equivalent to @w{@samp{while (x > 0)}}.  If the
  922. X@var{condition} is omitted, it is treated as @var{true}, effectively
  923. Xyielding an infinite loop.@refill
  924. X
  925. XIn most cases, a @code{for} loop is an abbreviation for a @code{while}
  926. Xloop, as shown here:
  927. X
  928. X@example
  929. X@var{initialization}
  930. Xwhile (@var{condition}) @{
  931. X  @var{body}
  932. X  @var{increment}
  933. X@}
  934. X@end example
  935. X
  936. X@noindent
  937. XThe only exception is when the @code{continue} statement
  938. X(@pxref{Continue Statement}) is used inside the loop; changing a
  939. X@code{for} statement to a @code{while} statement in this way can change
  940. Xthe effect of the @code{continue} statement inside the loop.
  941. X
  942. XThere is an alternate version of the @code{for} loop, for iterating over
  943. Xall the indices of an array:
  944. X
  945. X@example
  946. Xfor (i in array)
  947. X    @var{do something with} array[i]
  948. X@end example
  949. X
  950. X@noindent
  951. X@xref{Arrays}, for more information on this version of the @code{for} loop.
  952. X
  953. XThe @code{awk} language has a @code{for} statement in addition to a
  954. X@code{while} statement because often a @code{for} loop is both less work to
  955. Xtype and more natural to think of.  Counting the number of iterations is
  956. Xvery common in loops.  It can be easier to think of this counting as part
  957. Xof looping rather than as something to do inside the loop.
  958. X
  959. XThe next section has more complicated examples of @code{for} loops.
  960. X
  961. X@node Break Statement, Continue Statement, For Statement, Statements
  962. X@section The @code{break} Statement
  963. X@cindex @code{break} statement
  964. X@cindex loops, exiting
  965. X
  966. XThe @code{break} statement jumps out of the innermost @code{for},
  967. X@code{while}, or @code{do}-@code{while} loop that encloses it.  The
  968. Xfollowing example finds the smallest divisor of any integer, and also
  969. Xidentifies prime numbers:@refill
  970. X
  971. X@example
  972. Xawk '# find smallest divisor of num
  973. X     @{ num = $1
  974. X       for (div = 2; div*div <= num; div++)
  975. X         if (num % div == 0)
  976. X           break
  977. X       if (num % div == 0)
  978. X         printf "Smallest divisor of %d is %d\n", num, div
  979. X       else
  980. X         printf "%d is prime\n", num  @}'
  981. X@end example
  982. X
  983. XWhen the remainder is zero in the first @code{if} statement, @code{awk}
  984. Ximmediately @dfn{breaks out} of the containing @code{for} loop.  This means
  985. Xthat @code{awk} proceeds immediately to the statement following the loop
  986. Xand continues processing.  (This is very different from the @code{exit}
  987. Xstatement (@pxref{Exit Statement}) which stops the entire @code{awk}
  988. Xprogram.)@refill
  989. X
  990. XHere is another program equivalent to the previous one.  It illustrates how
  991. Xthe @var{condition} of a @code{for} or @code{while} could just as well be
  992. Xreplaced with a @code{break} inside an @code{if}:
  993. X
  994. X@example
  995. Xawk '# find smallest divisor of num
  996. X     @{ num = $1
  997. X       for (div = 2; ; div++) @{
  998. X         if (num % div == 0) @{
  999. X           printf "Smallest divisor of %d is %d\n", num, div
  1000. X           break
  1001. X         @}
  1002. X         if (div*div > num) @{
  1003. X           printf "%d is prime\n", num
  1004. X           break
  1005. X         @}
  1006. X       @}
  1007. X@}'
  1008. X@end example
  1009. X
  1010. X@node Continue Statement, Next Statement, Break Statement, Statements
  1011. X@section The @code{continue} Statement
  1012. X
  1013. X@cindex @code{continue} statement
  1014. XThe @code{continue} statement, like @code{break}, is used only inside
  1015. X@code{for}, @code{while}, and @code{do}-@code{while} loops.  It skips
  1016. Xover the rest of the loop body, causing the next cycle around the loop
  1017. Xto begin immediately.  Contrast this with @code{break}, which jumps out
  1018. Xof the loop altogether.  Here is an example:@refill
  1019. X
  1020. X@example
  1021. X# print names that don't contain the string "ignore"
  1022. X
  1023. X# first, save the text of each line
  1024. X@{ names[NR] = $0 @}
  1025. X
  1026. X# print what we're interested in
  1027. XEND @{
  1028. X   for (x in names) @{
  1029. X       if (names[x] ~ /ignore/)
  1030. X           continue
  1031. X       print names[x]
  1032. X   @}
  1033. X@}
  1034. X@end example
  1035. X
  1036. XIf one of the input records contains the string @samp{ignore}, this
  1037. Xexample skips the print statement for that record, and continues back to
  1038. Xthe first statement in the loop.
  1039. X
  1040. XThis isn't a practical example of @code{continue}, since it would be
  1041. Xjust as easy to write the loop like this:
  1042. X
  1043. X@example
  1044. Xfor (x in names)
  1045. X  if (names[x] !~ /ignore/)
  1046. X    print names[x]
  1047. X@end example
  1048. X
  1049. XThe @code{continue} statement in a @code{for} loop directs @code{awk} to
  1050. Xskip the rest of the body of the loop, and resume execution with the
  1051. Xincrement-expression of the @code{for} statement.  The following program
  1052. Xillustrates this fact:@refill
  1053. X
  1054. X@example
  1055. Xawk 'BEGIN @{
  1056. X     for (x = 0; x <= 20; x++) @{
  1057. X         if (x == 5)
  1058. X             continue
  1059. X         printf ("%d ", x)
  1060. X     @}
  1061. X     print ""
  1062. X@}'
  1063. X@end example
  1064. X
  1065. X@noindent
  1066. XThis program prints all the numbers from 0 to 20, except for 5, for
  1067. Xwhich the @code{printf} is skipped.  Since the increment @code{x++}
  1068. Xis not skipped, @code{x} does not remain stuck at 5.  Contrast the
  1069. X@code{for} loop above with the @code{while} loop:
  1070. X
  1071. X@example
  1072. Xawk 'BEGIN @{
  1073. X     x = 0
  1074. X     while (x <= 20) @{
  1075. X         if (x == 5)
  1076. X             continue
  1077. X         printf ("%d ", x)
  1078. X         x++
  1079. X     @}
  1080. X     print ""
  1081. X@}'
  1082. X@end example
  1083. X
  1084. X@noindent
  1085. XThis program loops forever once @code{x} gets to 5.
  1086. X
  1087. X@node Next Statement, Exit Statement, Continue Statement, Statements
  1088. X@section The @code{next} Statement
  1089. X@cindex @code{next} statement
  1090. X
  1091. XThe @code{next} statement forces @code{awk} to immediately stop processing
  1092. Xthe current record and go on to the next record.  This means that no
  1093. Xfurther rules are executed for the current record.  The rest of the
  1094. Xcurrent rule's action is not executed either.
  1095. X
  1096. XContrast this with the effect of the @code{getline} function
  1097. X(@pxref{Getline}).  That too causes @code{awk} to read the next record
  1098. Ximmediately, but it does not alter the flow of control in any way.  So
  1099. Xthe rest of the current action executes with a new input record.
  1100. X
  1101. XAt the grossest level, @code{awk} program execution is a loop that reads
  1102. Xan input record and then tests each rule's pattern against it.  If you
  1103. Xthink of this loop as a @code{for} statement whose body contains the
  1104. Xrules, then the @code{next} statement is analogous to a @code{continue}
  1105. Xstatement: it skips to the end of the body of this implicit loop, and
  1106. Xexecutes the increment (which reads another record).
  1107. X
  1108. XFor example, if your @code{awk} program works only on records with four
  1109. Xfields, and you don't want it to fail when given bad input, you might
  1110. Xuse this rule near the beginning of the program:
  1111. X
  1112. X@example
  1113. XNF != 4 @{
  1114. X  printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr"
  1115. X  next
  1116. X@}
  1117. X@end example
  1118. X
  1119. X@noindent
  1120. Xso that the following rules will not see the bad record.  The error
  1121. Xmessage is redirected to the standard error output stream, as error
  1122. Xmessages should be.  @xref{Special Files}.
  1123. X
  1124. XThe @code{next} statement is not allowed in a @code{BEGIN} or @code{END}
  1125. Xrule.
  1126. X
  1127. X@node Exit Statement, , Next Statement, Statements
  1128. X@section The @code{exit} Statement
  1129. X
  1130. X@cindex @code{exit} statement
  1131. XThe @code{exit} statement causes @code{awk} to immediately stop
  1132. Xexecuting the current rule and to stop processing input; any remaining input
  1133. Xis ignored.@refill
  1134. X
  1135. XIf an @code{exit} statement is executed from a @code{BEGIN} rule the
  1136. Xprogram stops processing everything immediately.  No input records are
  1137. Xread.  However, if an @code{END} rule is present, it is executed
  1138. X(@pxref{BEGIN/END}).
  1139. X
  1140. XIf @code{exit} is used as part of an @code{END} rule, it causes
  1141. Xthe program to stop immediately.
  1142. X
  1143. XAn @code{exit} statement that is part an ordinary rule (that is, not part
  1144. Xof a @code{BEGIN} or @code{END} rule) stops the execution of any further
  1145. Xautomatic rules, but the @code{END} rule is executed if there is one.
  1146. XIf you don't want the @code{END} rule to do its job in this case, you
  1147. Xcan set a variable to nonzero before the @code{exit} statement, and check
  1148. Xthat variable in the @code{END} rule.
  1149. X
  1150. XIf an argument is supplied to @code{exit}, its value is used as the exit
  1151. Xstatus code for the @code{awk} process.  If no argument is supplied,
  1152. X@code{exit} returns status zero (success).@refill
  1153. X
  1154. XFor example, let's say you've discovered an error condition you really
  1155. Xdon't know how to handle.  Conventionally, programs report this by
  1156. Xexiting with a nonzero status.  Your @code{awk} program can do this
  1157. Xusing an @code{exit} statement with a nonzero argument.  Here's an
  1158. Xexample of this:@refill
  1159. X
  1160. X@example
  1161. XBEGIN @{
  1162. X       if (("date" | getline date_now) < 0) @{
  1163. X         print "Can't get system date" > "/dev/stderr"
  1164. X         exit 4
  1165. X       @}
  1166. X@}
  1167. X@end example
  1168. X
  1169. X@node Arrays, Built-in, Statements, Top
  1170. X@chapter Arrays in @code{awk}
  1171. X
  1172. XAn @dfn{array} is a table of various values, called @dfn{elements}.  The
  1173. Xelements of an array are distinguished by their @dfn{indices}.  Indices
  1174. Xmay be either numbers or strings.  Each array has a name, which looks
  1175. Xlike a variable name, but must not be in use as a variable name in the
  1176. Xsame @code{awk} program.
  1177. X
  1178. X@menu
  1179. X* Intro: Array Intro.      Basic facts about arrays in @code{awk}.
  1180. X* Reference to Elements::  How to examine one element of an array.
  1181. X* Assigning Elements::     How to change an element of an array.
  1182. X* Example: Array Example.  Sample program explained.
  1183. X
  1184. X* Scanning an Array::      A variation of the @code{for} statement.  It loops
  1185. X                           through the indices of an array's existing elements.
  1186. X
  1187. X* Delete::                 The @code{delete} statement removes an element from an array.
  1188. X
  1189. X* Multi-dimensional::      Emulating multi-dimensional arrays in @code{awk}.
  1190. X* Multi-scanning::         Scanning multi-dimensional arrays.
  1191. X@end menu
  1192. X
  1193. X@node Array Intro, Reference to Elements, Arrays, Arrays
  1194. X@section Introduction to Arrays
  1195. X
  1196. X@cindex arrays
  1197. XThe @code{awk} language has one-dimensional @dfn{arrays} for storing groups
  1198. Xof related strings or numbers.
  1199. X
  1200. XEvery @code{awk} array must have a name.  Array names have the same
  1201. Xsyntax as variable names; any valid variable name would also be a valid
  1202. Xarray name.  But you cannot use one name in both ways (as an array and
  1203. Xas a variable) in one @code{awk} program.
  1204. X
  1205. XArrays in @code{awk} superficially resemble arrays in other programming
  1206. Xlanguages; but there are fundamental differences.  In @code{awk}, you
  1207. Xdon't need to specify the size of an array before you start to use it.
  1208. XWhat's more, in @code{awk} any number or even a string may be used as an
  1209. Xarray index.
  1210. X
  1211. XIn most other languages, you have to @dfn{declare} an array and specify
  1212. Xhow many elements or components it has.  In such languages, the
  1213. Xdeclaration causes a contiguous block of memory to be allocated for that
  1214. Xmany elements.  An index in the array must be a positive integer; for
  1215. Xexample, the index 0 specifies the first element in the array, which is
  1216. Xactually stored at the beginning of the block of memory.  Index 1
  1217. Xspecifies the second element, which is stored in memory right after the
  1218. Xfirst element, and so on.  It is impossible to add more elements to the
  1219. Xarray, because it has room for only as many elements as you declared.
  1220. X
  1221. XA contiguous array of four elements might look like this, conceptually,
  1222. Xif the element values are 8, @code{"foo"}, @code{""} and 30:@refill
  1223. X
  1224. X@example
  1225. X+---------+---------+--------+---------+
  1226. X|    8    |  "foo"  |   ""   |    30   |    @r{value}
  1227. X+---------+---------+--------+---------+
  1228. X     0         1         2         3        @r{index}
  1229. X@end example
  1230. X
  1231. X@noindent
  1232. XOnly the values are stored; the indices are implicit from the order of
  1233. Xthe values.  8 is the value at index 0, because 8 appears in the
  1234. Xposition with 0 elements before it.
  1235. X
  1236. X@cindex arrays, definition of
  1237. X@cindex associative arrays
  1238. XArrays in @code{awk} are different: they are @dfn{associative}.  This means
  1239. Xthat each array is a collection of pairs: an index, and its corresponding
  1240. Xarray element value:
  1241. X
  1242. X@example
  1243. X@r{Element} 4     @r{Value} 30
  1244. X@r{Element} 2     @r{Value} "foo"
  1245. X@r{Element} 1     @r{Value} 8
  1246. X@r{Element} 3     @r{Value} ""
  1247. X@end example
  1248. X
  1249. X@noindent
  1250. XWe have shown the pairs in jumbled order because their order doesn't
  1251. Xmean anything.
  1252. X
  1253. XOne advantage of an associative array is that new pairs can be added
  1254. Xat any time.  For example, suppose we add to that array a tenth element
  1255. Xwhose value is @w{@code{"number ten"}}.  The result is this:
  1256. X
  1257. X@example
  1258. X@r{Element} 10    @r{Value} "number ten"
  1259. X@r{Element} 4     @r{Value} 30
  1260. X@r{Element} 2     @r{Value} "foo"
  1261. X@r{Element} 1     @r{Value} 8
  1262. X@r{Element} 3     @r{Value} ""
  1263. X@end example
  1264. X
  1265. X@noindent
  1266. XNow the array is @dfn{sparse} (i.e., some indices are missing): it has
  1267. Xelements 4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.@refill
  1268. X
  1269. XAnother consequence of associative arrays is that the indices don't
  1270. Xhave to be positive integers.  Any number, or even a string, can be
  1271. Xan index.  For example, here is an array which translates words from
  1272. XEnglish into French:
  1273. X
  1274. X@example
  1275. X@r{Element} "dog" @r{Value} "chien"
  1276. X@r{Element} "cat" @r{Value} "chat"
  1277. X@r{Element} "one" @r{Value} "un"
  1278. X@r{Element} 1     @r{Value} "un"
  1279. X@end example
  1280. X
  1281. X@noindent
  1282. XHere we decided to translate the number 1 in both spelled-out and
  1283. Xnumeric form---thus illustrating that a single array can have both
  1284. Xnumbers and strings as indices.
  1285. X
  1286. XWhen @code{awk} creates an array for you, e.g., with the @code{split}
  1287. Xbuilt-in function (@pxref{String Functions}), that array's indices
  1288. Xare consecutive integers starting at 1.
  1289. X
  1290. X@node Reference to Elements, Assigning Elements, Array Intro, Arrays
  1291. X@section Referring to an Array Element
  1292. X@cindex array reference
  1293. X@cindex element of array
  1294. X@cindex reference to array
  1295. X
  1296. XThe principal way of using an array is to refer to one of its elements.
  1297. XAn array reference is an expression which looks like this:
  1298. X
  1299. X@example
  1300. X@var{array}[@var{index}]
  1301. X@end example
  1302. X
  1303. X@noindent
  1304. XHere @var{array} is the name of an array.  The expression @var{index} is
  1305. Xthe index of the element of the array that you want.
  1306. X
  1307. XThe value of the array reference is the current value of that array
  1308. Xelement.  For example, @code{foo[4.3]} is an expression for the element
  1309. Xof array @code{foo} at index 4.3.
  1310. X
  1311. XIf you refer to an array element that has no recorded value, the value
  1312. Xof the reference is @code{""}, the null string.  This includes elements
  1313. Xto which you have not assigned any value, and elements that have been
  1314. Xdeleted (@pxref{Delete}).  Such a reference automatically creates that
  1315. Xarray element, with the null string as its value.  (In some cases,
  1316. Xthis is unfortunate, because it might waste memory inside @code{awk}).
  1317. X
  1318. X@cindex arrays, determining presence of elements
  1319. XYou can find out if an element exists in an array at a certain index with
  1320. Xthe expression:
  1321. X
  1322. X@example
  1323. X@var{index} in @var{array}
  1324. X@end example
  1325. X
  1326. X@noindent
  1327. XThis expression tests whether or not the particular index exists,
  1328. Xwithout the side effect of creating that element if it is not present.
  1329. XThe expression has the value 1 (true) if @code{@var{array}[@var{index}]}
  1330. Xexists, and 0 (false) if it does not exist.@refill
  1331. X
  1332. XFor example, to test whether the array @code{frequencies} contains the
  1333. Xindex @code{"2"}, you could write this statement:@refill
  1334. X
  1335. X@example
  1336. Xif ("2" in frequencies) print "Subscript \"2\" is present."
  1337. X@end example
  1338. X
  1339. XNote that this is @emph{not} a test of whether or not the array
  1340. X@code{frequencies} contains an element whose @emph{value} is @code{"2"}.
  1341. X(There is no way to do that except to scan all the elements.)  Also, this
  1342. X@emph{does not} create @code{frequencies["2"]}, while the following
  1343. X(incorrect) alternative would do so:@refill
  1344. X
  1345. X@example
  1346. Xif (frequencies["2"] != "") print "Subscript \"2\" is present."
  1347. X@end example
  1348. X
  1349. X@node Assigning Elements, Array Example, Reference to Elements, Arrays
  1350. X@section Assigning Array Elements
  1351. X@cindex array assignment
  1352. X@cindex element assignment
  1353. X
  1354. XArray elements are lvalues: they can be assigned values just like
  1355. X@code{awk} variables:
  1356. X
  1357. X@example
  1358. X@var{array}[@var{subscript}] = @var{value}
  1359. X@end example
  1360. X
  1361. X@noindent
  1362. XHere @var{array} is the name of your array.  The expression
  1363. X@var{subscript} is the index of the element of the array that you want
  1364. Xto assign a value.  The expression @var{value} is the value you are
  1365. Xassigning to that element of the array.@refill
  1366. X
  1367. X@node Array Example, Scanning an Array, Assigning Elements, Arrays
  1368. X@section Basic Example of an Array
  1369. X
  1370. XThe following program takes a list of lines, each beginning with a line
  1371. Xnumber, and prints them out in order of line number.  The line numbers are
  1372. Xnot in order, however, when they are first read:  they are scrambled.  This
  1373. Xprogram sorts the lines by making an array using the line numbers as
  1374. Xsubscripts.  It then prints out the lines in sorted order of their numbers.
  1375. XIt is a very simple program, and gets confused if it encounters repeated
  1376. Xnumbers, gaps, or lines that don't begin with a number.@refill
  1377. X
  1378. X@example
  1379. X@{
  1380. X  if ($1 > max)
  1381. X    max = $1
  1382. X  arr[$1] = $0
  1383. X@}
  1384. X
  1385. XEND @{
  1386. X  for (x = 1; x <= max; x++)
  1387. X    print arr[x]
  1388. X@}
  1389. X@end example
  1390. X
  1391. X@ignore
  1392. XThe first rule just initializes the variable @code{max}.  (This is not
  1393. Xstrictly necessary, since an uninitialized variable has the null string
  1394. Xas its value, and the null string is effectively zero when used in
  1395. Xa context where a number is required.)
  1396. X@end ignore
  1397. X
  1398. XThe first rule keeps track of the largest line number seen so far;
  1399. Xit also stores each line into the array @code{arr}, at an index that
  1400. Xis the line's number.
  1401. X
  1402. XThe second rule runs after all the input has been read, to print out
  1403. Xall the lines.
  1404. X
  1405. XWhen this program is run with the following input:
  1406. X
  1407. X@example
  1408. X5  I am the Five man
  1409. X2  Who are you?  The new number two!
  1410. X4  . . . And four on the floor
  1411. X1  Who is number one?
  1412. X3  I three you.
  1413. X@end example
  1414. X
  1415. X@noindent
  1416. Xits output is this:
  1417. X
  1418. X@example
  1419. X1  Who is number one?
  1420. X2  Who are you?  The new number two!
  1421. X3  I three you.
  1422. X4  . . . And four on the floor
  1423. X5  I am the Five man
  1424. X@end example
  1425. X
  1426. END_OF_FILE
  1427.   if test 49666 -ne `wc -c <'./gawk.texinfo.04'`; then
  1428.     echo shar: \"'./gawk.texinfo.04'\" unpacked with wrong size!
  1429.   fi
  1430.   # end of './gawk.texinfo.04'
  1431. fi
  1432. if test -f './missing.d/strtod.c' -a "${1}" != "-c" ; then 
  1433.   echo shar: Will not clobber existing file \"'./missing.d/strtod.c'\"
  1434. else
  1435.   echo shar: Extracting \"'./missing.d/strtod.c'\" \(2023 characters\)
  1436.   sed "s/^X//" >'./missing.d/strtod.c' <<'END_OF_FILE'
  1437. X/*
  1438. X * strtod.c
  1439. X *
  1440. X * Stupid version of System V strtod(3) library routine.
  1441. X * Does no overflow/underflow checking.
  1442. X *
  1443. X * A real number is defined to be
  1444. X *    optional leading white space
  1445. X *    optional sign
  1446. X *    string of digits with optional decimal point
  1447. X *    optional 'e' or 'E'
  1448. X *        followed by optional sign or space
  1449. X *        followed by an integer
  1450. X *
  1451. X * if ptr is not NULL a pointer to the character terminating the
  1452. X * scan is returned in *ptr.  If no number formed, *ptr is set to str
  1453. X * and 0 is returned.
  1454. X *
  1455. X * For speed, we don't do the conversion ourselves.  Instead, we find
  1456. X * the end of the number and then call atof() to do the dirty work.
  1457. X * This bought us a 10% speedup on a sample program at uunet.uu.net.
  1458. X */
  1459. X
  1460. X#include <ctype.h>
  1461. X
  1462. Xextern double atof();
  1463. X
  1464. Xdouble
  1465. Xstrtod (s, ptr)
  1466. Xregister char *s, **ptr;
  1467. X{
  1468. X    double ret = 0.0;
  1469. X    char *start = s;
  1470. X    char *begin = NULL;
  1471. X    int success = 0;
  1472. X
  1473. X    /* optional white space */
  1474. X    while (isspace(*s))
  1475. X        s++;
  1476. X
  1477. X    /* optional sign */
  1478. X    if (*s == '+' || *s == '-') {
  1479. X        s++;
  1480. X        if (*(s-1) == '-')
  1481. X            begin = s - 1;
  1482. X        else
  1483. X            begin = s;
  1484. X    }
  1485. X
  1486. X    /* string of digits with optional decimal point */
  1487. X    if (isdigit(*s) && ! begin)
  1488. X        begin = s;
  1489. X
  1490. X    while (isdigit(*s)) {
  1491. X        s++;
  1492. X        success++;
  1493. X    }
  1494. X
  1495. X    if (*s == '.') {
  1496. X        if (! begin)
  1497. X            begin = s;
  1498. X        s++;
  1499. X        while (isdigit(*s))
  1500. X            s++;
  1501. X        success++;
  1502. X    }
  1503. X
  1504. X    if (s == start || success == 0)        /* nothing there */
  1505. X        goto out;
  1506. X
  1507. X    /*
  1508. X      *    optional 'e' or 'E'
  1509. X     *        followed by optional sign or space
  1510. X     *        followed by an integer
  1511. X     */
  1512. X
  1513. X    if (*s == 'e' || *s == 'E') {
  1514. X        s++;
  1515. X
  1516. X        /* XXX - atof probably doesn't allow spaces here */
  1517. X        while (isspace(*s))
  1518. X            s++;
  1519. X
  1520. X        if (*s == '+' || *s == '-')
  1521. X            s++;
  1522. X
  1523. X        while (isdigit(*s))
  1524. X            s++;
  1525. X    }
  1526. X
  1527. X    /* go for it */
  1528. X    ret = atof(begin);
  1529. X
  1530. Xout:
  1531. X    if (! success)
  1532. X        s = start;    /* in case all we did was skip whitespace */
  1533. X
  1534. X    if (ptr)
  1535. X        *ptr = s;
  1536. X
  1537. X    return ret;
  1538. X}
  1539. X
  1540. X#ifdef TEST
  1541. Xmain (argc, argv)
  1542. Xint argc;
  1543. Xchar **argv;
  1544. X{
  1545. X    double d;
  1546. X    char *p;
  1547. X
  1548. X    for (argc--, argv++; argc; argc--, argv++) {
  1549. X        d = strtod (*argv, & p);
  1550. X        printf ("%lf [%s]\n", d, p);
  1551. X    }
  1552. X}
  1553. X#endif
  1554. END_OF_FILE
  1555.   if test 2023 -ne `wc -c <'./missing.d/strtod.c'`; then
  1556.     echo shar: \"'./missing.d/strtod.c'\" unpacked with wrong size!
  1557.   fi
  1558.   # end of './missing.d/strtod.c'
  1559. fi
  1560. echo shar: End of archive 3 \(of 16\).
  1561. cp /dev/null ark3isdone
  1562. MISSING=""
  1563. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  1564.     if test ! -f ark${I}isdone ; then
  1565.     MISSING="${MISSING} ${I}"
  1566.     fi
  1567. done
  1568. if test "${MISSING}" = "" ; then
  1569.     echo You have unpacked all 16 archives.
  1570.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1571. else
  1572.     echo You still must unpack the following archives:
  1573.     echo "        " ${MISSING}
  1574. fi
  1575. exit 0
  1576. exit 0 # Just in case...
  1577.